﻿namespace Vboot.Core.Module.Bpm;

public class BpmNodeHistService : ITransient
{
    private readonly SqlSugarRepository<BpmNodeHist> _repo;

    public BpmNodeHistService(SqlSugarRepository<BpmNodeHist> repo)
    {
        _repo = repo;
    }

    public async Task SaveStartNode(Zbpm zbpm)
    {
        BpmNodeHist startNode = new BpmNodeHist();
        startNode.facno = "NS";
        startNode.facna = "开始节点";
        startNode.facty = "start";
        startNode.proid = zbpm.proid;
        startNode.state = "30";
        startNode.entim = DateTime.Now;
        startNode.tarno = "N1";
        startNode.tarna = "起草节点";
        startNode.id = YitIdHelper.NextId() + "";
        await _repo.InsertAsync(startNode);
    }

    public async Task SaveDraftNode(Zbpm zbpm, Znode znode)
    {
        BpmNodeHist draftNode = new BpmNodeHist();
        draftNode.facno = "N1";
        draftNode.facna = "起草节点";
        draftNode.facty = "draft";
        draftNode.proid = zbpm.proid;
        draftNode.state = "30";
        draftNode.id = znode.nodid;
        draftNode.entim = DateTime.Now;
        draftNode.tarno = znode.tarno;
        draftNode.tarna = znode.tarna;
        await _repo.InsertAsync(draftNode);
    }

    public async Task<string> SaveEndNode(Zbpm zbpm)
    {
        BpmNodeHist endNode = new BpmNodeHist();
        endNode.facno = "NE";
        endNode.facna = "结束节点";
        endNode.facty = "end";
        endNode.proid = zbpm.proid;
        endNode.state = "30";
        endNode.id = YitIdHelper.NextId() + "";
        endNode.entim = DateTime.Now;
        ;
        await _repo.InsertAsync(endNode);
        return endNode.id;
    }

    public async Task SaveNodeList(Zbpm zbpm, List<Znode> list)
    {
        foreach (Znode znode in list)
        {
            BpmNodeHist node = new BpmNodeHist();
            node.facno = znode.facno;
            node.facna = znode.facna;
            node.facty = znode.facty;
            node.proid = zbpm.proid;
            node.tarno = znode.tarno;
            node.tarna = znode.tarna;
            node.state = "30";
            node.id = YitIdHelper.NextId() + "";
            node.entim = DateTime.Now;
            await _repo.InsertAsync(node);
        }
    }

    public async Task<BpmNodeHist> SaveNode(BpmNodeMain main)
    {
        BpmNodeHist node = new BpmNodeHist();
        node.id = main.id;
        node.facno = main.facno;
        node.facna = main.facna;
        node.facty = main.facty;
        node.flway = main.flway;
        node.proid = main.proid;
        node.state = "20";
        await _repo.InsertAsync(node);
        return node;
    }

    public async Task<BpmNodeHist> FindOne(string id)
    {
        return await _repo.GetSingleAsync(t => t.id == id);
    }

    public async Task Update(BpmNodeHist hist)
    {
        await _repo.Context.Updateable(hist).ExecuteCommandAsync();
    }
}